<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 */
namespace app\api\controller;

use Mscore\Core\Controller;
use app\api\model\Login as LoginModel;
use app\api\model\Withdraw as WithdrawModel;
use app\api\model\Recharge as RechargeModel;
use app\api\model\Apply as ApplyModel;
use app\api\model\Common as CommonModel;
use Mscore\Core\Util\Util;
use Mscore\Core\Lang;

class FinanceController extends Controller{

    private $login;
    private $error;
    private $success;
    public function __construct()  
    {    
        $this->login = (new LoginModel)->isAuth();
        $this->header =get_all_headers();
        $this->header['language']=isset($this->header['language'])&&!empty($this->header['language'])?$this->header['language']:config('langs.default');
        Lang::init($this->header['language']);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }
    /**
     * 充值列表
     * @param array $recharge 
     * @param array $where 
     */ 
    public function rechargelist(){  
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $datalist = (new RechargeModel())->list($where);
                $this->success['data']=$datalist['datalist'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1 and a.aid= '.$this->login['aid'];
                $datalist = (new RechargeModel())->list($where,$page,$limit);
                foreach ($datalist['datalist'] as $key => $value) {
                    $datalist['datalist'][$key]['createtime']=date('y-m-d H:i',strtotime($value['createtime']));
                }
                $this->success['data']=$datalist['datalist'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }
    /**
     * 充值
     * @param array $recharge 
     * @param array $where 
     */ 
    public function recharge(){
        $params = post();
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        if(empty($params['money'])) return $this->echoJson(Lang::get('Remoneyempty'));
        $payment = (new CommonModel())->getBaseinfo('keyname="payment"','content')['content'];
        $codes='';$rate=1;$voucherimg=1;$gift=5;
        if(!empty($payment)){
            $currency = $payment['currency'];
            $voucherimg = $payment['voucherimg'];
            $gift = $payment['gift'];
            $rate = (new CommonModel())->getexchangeinfo(' codes= "'.$currency.'"','rate')['rate']; //平臺貨幣匯率
        }
        if(empty($params['file_url'])&&$voucherimg<2) return $this->echoJson(Lang::get('Refileempty'));
        $params['aid']=$this->login['aid'];
        $params['pid']=$this->login['pid'];
        $params['codes'] = $currency;
        $rates = (new CommonModel())->getexchangeinfo(' codes= "'.$params['currency'].'"','rate')['rate']; //入金貨幣匯率
        $ratebase = (new CommonModel())->getexchangeinfo(' status>0 and dels<1 and defualt>0 ','rate')['rate']; //標準貨幣匯率
        $params['rate'] = round(($ratebase/$rates)*$rate*100)/100;
        $params['integra'] = round(($params['money']*$gift))/100;
        $info = (new RechargeModel())->save($params);
        switch (true) {
            case $info>0:
                logrecord(
                    '账户id'.$params['aid'].' 入金金额：'.$params['money'].';赠送:'.$params['integra'].';操作：成功',
                    $this->login
                );
                return $this->echojson($this->success);
                break;
            default:
                logrecord(
                    '账户id'.$params['aid'].' 入金金额：'.$params['money'].';赠送:'.$params['integra'].';操作：失败',
                    $this->login
                );
                return $this->echojson($this->error);
                break;
        }
    }
    /**
     * 充值对应接口
     * @param array $recharge 
     * @param array $where 
     */ 
    public function rechargeacc(){
        $info=(new CommonModel())->getBaseinfo('keyname="payconfig"',['content'])['content'];
        $infos=[];
        $i=0;
        foreach ($info as $key => $value) {
            $infos[$i]=['id'=>$key,'value'=>$value];
            $i++;
        }
        unset($info);
        $this->success['data']=$infos;
        return $this->echojson($this->success);
    }
    /**
     * 充值列表
     * @param array $recharge 
     * @param array $where 
     */ 
    public function withdrawlist(){  
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $datalist = (new WithdrawModel())->list($where);
                $this->success['data']=$datalist['datalist'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1 and a.type=1 and a.aid= '.$this->login['aid'];
                $datalist = (new WithdrawModel())->list($where,$page,$limit);
                foreach ($datalist['datalist'] as $key => $value) {
                    $datalist['datalist'][$key]['createtime']=date('y-m-d H:i',strtotime($value['createtime']));
                }
                $this->success['data']=$datalist['datalist'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }
    /**
     * 提现申请
     * @param array $withdraw 
     * @param array $where 
     */ 
    public function withdraw(){
        $params = post();
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        if(empty($params['money'])) return $this->echoJson(Lang::get('Remoneyempty'));
        if(empty($params['payment'])) return $this->echoJson(Lang::get('Bankempty'));
        $payment = (new CommonModel())->getBaseinfo('keyname="payment"','content')['content'];
        if(empty($params['codes'])){
            if(!isset($payment['currency'])|| empty($payment['currency'])) return $this->echoJson(Lang::get('Currerror'));
            $params['codes']=$payment['currency'];
        } 
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','paypwd','amount','integra']);
        if(($user['amount']-$params['money'])<0) return $this->echoJson(Lang::get('Refileamount'));
        //判斷支付密碼及驗證
        $edituser=(new CommonModel())->getBaseinfo('keyname="edituser"','content')['content'];
        $withdrawal = 1;
        if(isset($edituser['withdrawal'])&&!empty($edituser['withdrawal'])){$withdrawal=$edituser['withdrawal'];}
        if($withdrawal==1){
            if(empty($user['paypwd'])) return $this->echoJson(Lang::get('Paypwdset'));
            if(empty($params['paypwd'])) return $this->echoJson(Lang::get('Paypwdempty'));
            if (!Util::passwordVerify($params['paypwd'], $user['paypwd'])) return $this->echojson(Lang::get('Paypwderror'));
        }
        $params['aid']=$this->login['aid'];
        $params['pid']=$this->login['pid'];

        // $payment = (new CommonModel())->getBaseinfo('keyname="payment"','content')['content'];
        $codes='';$gift=0;$rate=1;$withgift=1;
        if(!empty($payment)){
            $currency = $payment['currency'];
            $feerate = $payment['withdrawal'];
            $withgift = $payment['withgift'];
            $rate = (new CommonModel())->getexchangeinfo(' codes= "'.$currency.'"','rate')['rate']; //平臺貨幣匯率
        }
        $params['currency']=$currency;
        $rates = (new CommonModel())->getexchangeinfo(' codes= "'.$params['codes'].'"','rate')['rate']; //體現貨幣匯率
        $ratebase = (new CommonModel())->getexchangeinfo(' status>0 and dels<1 and defualt>0 ','rate')['rate']; //標準貨幣匯率
        $params['rate'] = round(($ratebase/$rate)*$rates*100)/100;
        $params['fee'] = round($params['money']*$feerate)/100;
        $params['withgift']=$withgift;
        switch ($withgift) {
            case '1':
                $amount = $user['amount']-$params['money'];
                if($amount<=0){
                    $amount = 0;
                    $integra = $user['amount']+$user['integra']-$params['money'];
                    $params['money'] = $user['amount'];
                    $params['integra']=$user['integra']-$integra;
                    if($integra<=0){
                        $integra=0;
                        $params['money'] = $user['amount'];
                        $params['integra'] = $user['integra'];
                    }
                }else{
                    $params['integra']=0;
                    $integra = $user['integra'];
                }
                break;
            case '2':
                $integra = $user['integra']-$params['money'];
                if($integra<=0){
                    $integra = 0;
                    $amount = $user['amount']+$user['integra']-$params['money'];
                    $params['integra']=$user['integra'];
                    $params['money']=$user['amount']-$amount;
                    if($amount<=0){
                        $amount=0;
                        $params['money'] = $user['amount'];
                        $params['integra']=$user['integra'];
                    }
                }else{
                    $amount = $user['amount'];
                    $params['integra']=$params['money'];
                    $params['money']=0;
                }
                break;
            default:
                $amount = $user['amount']-$params['money'];
                if($amount<=0){
                    $amount = 0;
                    $params['money'] = $user['amount'];
                }
                $integra = $user['integra'];
                $params['integra']=0;
                break;
        }
        $info = (new WithdrawModel())->save($params);
        switch (true) {
            case $info>0:
                (new CommonModel())->updateAccount('aid='.$this->login['aid'],['amount'=>$amount,'integra'=>$integra]);
                logrecord(
                    '账户id'.$params['aid'].' 出金金额：'.$params['money'].';出金赠送金额:'.$params['integra'].';操作：成功',
                    $this->login
                );
                return $this->echojson($this->success);
                break;
            default:
                logrecord(
                    '账户id'.$params['aid'].' 出金金额：'.$params['money'].';出金赠送金额:'.$params['integra'].';操作：失败',
                    $this->login
                );
                return $this->echojson($this->error);
                break;
        }
    } 
}